package buco.core.api;

import java.io.File;
import java.io.IOException;
import java.util.*;


/***
 * This command is used to add a Bundle (JAR-File) to the composition. 
 * 
 * @author Christopher
 *
 */
public class AddBundleCommand extends Command<AddBundleParameters, List<SemanticMessage>>
{
	private Bundle bundle; 	
	
	@Override
	public List<SemanticMessage> execute() throws IOException, DuplicateBundleException {		
		if(bundle == null) { 
			// Use File Management to store the file 
			int fileID = fileManager.addFile(parameters.getFileName(), parameters.getFile());		
			bundle = Bundle.fromJarFile(parameters.getFile());
			bundle.setFileID(fileID);
		}
		
		composition.addBundle(bundle);		
		
		List<IntegrityCheck> checks = IntegrityCheckRegistry.createIntegrityChecks();
		ArrayList<SemanticMessage> warnings = new ArrayList<SemanticMessage>();
		BundleIntegrityReport report = new BundleIntegrityReport(bundle);
		
		for(IntegrityCheck check : checks) {			
			check.bundleAdded(bundle, report);
		}
		
		warnings.addAll(report.getMessages()); 		
		return warnings;
	}
	
	@Override
	public void undo() {
		composition.removeBundle(bundle);
	}

	@Override
	public boolean canUndo() {		
		return true;
	}

}
